package com.xxxx.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.config.security.component.JwtTokenUtil;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.mapper.AdminRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.ReceiveChangePwdParams;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.utils.AssertUtil;
import com.xxxx.server.utils.PhoneUtil;
import com.xxxx.server.utils.QiniuCloudUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoubin
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

	@Resource
	private AdminMapper adminMapper;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Value("${jwt.tokenHead}")
	private String tokenHead;
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private AdminRoleMapper adminRoleMapper;

	private final String ADMIN_ROLE_ZH = "系统管理员";


	/**
	 * 登录之后返回token
	 * @param username
	 * @param password
	 * @param code
	 * @param request
	 * @return
	 */
	@Override
	public RespBean login(String username, String password, String code, HttpServletRequest request) {
		String captcha = (String) request.getSession().getAttribute("captcha");
		if (StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
			return RespBean.error("验证码输入错误，请重新输入！");
		}
		//登录
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		if (null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
			return RespBean.error("用户名或密码不正确");
		}
		if (!userDetails.isEnabled()){
			return RespBean.error("账号被禁用，请联系管理员！");
		}
		//更新security登录用户对象
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails
				,null,userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		//生成token
		String token = jwtTokenUtil.generateToken(userDetails);
		Map<String,String> tokenMap = new HashMap<>();
		tokenMap.put("token",token);
		tokenMap.put("tokenHead",tokenHead);
		return RespBean.success("登录成功",tokenMap);
	}

	/**
	 * 根据用户名获取用户
	 * @param username
	 * @return
	 */
	@Override
	public Admin getAdminByUserName(String username) {
		return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
	}

	/**
	 * 根据用户id查询角色列表
	 * @param adminId
	 * @return
	 */
	@Override
	public List<Role> getRoles(Integer adminId) {
		return roleMapper.getRoles(adminId);
	}

	@Override
	public List<Admin> getAdminsByNameLike(String keywords) {
		return null;
	}

	@Override
	public List<Admin> getAllAdmins(String data) {
		return null;
	}


	/*
     *
    个人中心
         修改信息
     */
	@Override
	public RespBean updateInfo(Admin admin) {

		//判断用户名、电话号码、手机号码、地址是否为空
		AssertUtil.isTrue(StringUtils.isBlank(admin.getName())
				||StringUtils.isBlank(admin.getTelephone())
				||StringUtils.isBlank(admin.getPhone())
				||StringUtils.isBlank(admin.getAddress()),"必填项不能为空！！！");
		//判断电话号码是否符合规则
		AssertUtil.isTrue(!PhoneUtil.isPhone(admin.getPhone()),"手机号码格式不正确！！！");
		//执行修改操作
		AssertUtil.isTrue(adminMapper.updateInfo(admin)<1,"修改失败！！！");
		return RespBean.success("修改成功！！！");
	}


	/*
     * 修改密码
         1. 判断用户ID是否为空
         2. 调用Dao层，通过用户ID查询用户对象
         3. 判断用户对象是否为空
         4. 判断原始密码是否为空
         5. 判断原始密码是否正确
         6. 判断新密码是否为空
         7. 判断新密码是否与原始密码相同
         8. 判断重复密码是否为空
         9. 判断重复密码是否与新密码相等
         10. 执行更新操作，判断受影响的行数
	 */

	@Override
	public RespBean updatePwd(ReceiveChangePwdParams params) {
		//1. 判断用户adminId是否为空
		AssertUtil.isTrue(params.getAdminId()==null,"待更新用户不存在！！！");
		//2. 调用Dao层，通过用户ID查询用户对象
		Admin admin = adminMapper.selectById(params.getAdminId());
		//3. 判断用户对象是否为空
		AssertUtil.isTrue(admin==null,"待更新用户不存在！！！");
		//4. 判断原始密码是否为空
		AssertUtil.isTrue(StringUtils.isBlank(params.getOldPass()),"原始密码不能为空！！！");
		//5. 判断原始密码是否正确
		AssertUtil.isTrue(passwordEncoder.encode(params.getOldPass()).equals(admin.getPassword()),"原密码不正确！！！");
		//  6. 判断新密码是否为空
		AssertUtil.isTrue(StringUtils.isBlank(params.getPass()),"新密码不能为空！！！");
		// 7. 判断新密码是否与原始密码相同
		AssertUtil.isTrue(passwordEncoder.encode(params.getPass()).equals(admin.getPassword()),"新密码与原密码相同，请重试！！！");
		//8. 判断重复密码是否为空
		AssertUtil.isTrue(StringUtils.isBlank(params.getCheckPass()),"确认密码不能为空！！！");
		//9. 判断重复密码是否与新密码相等
		AssertUtil.isTrue(passwordEncoder.encode(params.getCheckPass()).equals(passwordEncoder.encode(params.getPass())),"原密码和确认密码不一致！！！");
		//10. 执行更新操作，判断受影响的行数
		AssertUtil.isTrue(adminMapper.updatePwd(admin.getId(),passwordEncoder.encode(params.getPass()))<1,"修改失败！！！");
		return  RespBean.success("操作成功！！！");
	}



	@Override
	public RespBean upload(MultipartFile image, HttpServletRequest request) {

		RespBean respBean = new RespBean();
		if (image.isEmpty()){
			respBean.setCode(400);
			respBean.setMessage("文件为空，请重新上传");
			return  respBean;
		}

		try {
			byte[] bytes = image.getBytes();
			String imageName = UUID.randomUUID().toString();
			//使用base64方式上传到七牛云
			try {
				String userFace = QiniuCloudUtil.put64image(bytes, imageName);
				//获取SecurityContext中的用户对象
				Admin admin=(Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
				adminMapper.updateMyImg(admin.getId(),userFace);
				respBean.setCode(200);
				respBean.setMessage("文件上传成功");
				respBean.setObj(userFace);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			respBean.setCode(500);
			respBean.setMessage("系统异常，请稍后再试");
		}finally {
			return  respBean;
		}
	}

	/**
	 * 查询所有Admin
	 * @return
	 */
    @Override
    public List<Admin> queryAllAdmin() {
       return adminMapper.queryAllAdmin();
    }

    /**
	 * 查询t_admin表所有的数据
	 * @return
	 */
	/**
	 * 获取所有的用户列表
	 * @return
	 */
	@Override
	public List<Admin> list() {
		return adminMapper.queryAllAdmin();
	}







	//=================== 操作员管理模块 ================//
	//查询操作员的角色
	@Override
	public List<Admin> selectAdminInfo(String keywords) {

		List<Admin> admins = adminMapper.selectAdminInfo(keywords);

		//遍历查询admin下的角色集合。
		admins.forEach(t -> {
			//查询该admin下所有角色集合
			List<Role> roles = adminMapper.selectAdminRoleByAdminId(t.getId());
			//设置角色信息
			t.setRoles(roles);
		});

		return admins;
	}

	@Override
	public List<Role> selectAdminRole() {
		return adminMapper.selectAdminRole();
	}


	@Override
	public RespBean deleteAdminById(Integer id) {
		List<Integer> adminIds = adminMapper.getAdminId(id);
		for (Integer adminId : adminIds) {
			if (adminId == 1) {
				return RespBean.error("删除失败，不可删除系统管理员");
			}
		}
        int i2 = adminMapper.deleterolesByAdminId(id);
		int i3 = adminMapper.deleteMsgByAdminId(id);
		int i = adminMapper.deleteAdminById(id);
		if (i > 0 && i2 > 0 && i3 > 0 ) {
			return RespBean.success("删除成功啦！！！");
		}
		return RespBean.error("删除失败");
	}

	@Override
	public Integer enableChange(Map<String, Object> admin) {
		return null;
	}

	@Override
	public RespBean updateRolesById(Integer adminId, Integer[] rids) {
		if (adminId== 1) {
			return RespBean.error("无法修改系统管理员账户的角色");
		}
		//删除当前操作员的所有角色
		adminRoleMapper.deleteAllrolesByAdminId(adminId);
		//循环为当前用户添加角色

		if (rids.length < 1) {
			return RespBean.success("修改成功");
		} else {

			//用作判断
			int sum = 0;
			//循环添加
			for (Integer rid : rids
			) {
				int i = adminRoleMapper.AddRoleByAdminId(adminId, rid);
				sum = sum + i;
			}
			//判断
			if (sum == rids.length) {
				return RespBean.success("角色更改成功");
			} else {
				return RespBean.error("角色更改失败");
			}

		}
	}

	@Override
	public RespBean updateEnabledById(Map<String, Object> admin) {
		//管理员自己不能启用和禁用自己
		Integer adminId = (Integer) admin.get("id");
		if (adminId == 1) {
			return RespBean.error("管理员自己不能操作自己");
		}

		Boolean id = adminMapper.selectEnabledById((Integer) admin.get("id"));
		if (id) {
			Integer enabled = 0;
			int id1 = adminMapper.updateEnableById(enabled, (Integer) admin.get("id"));
			if (id1 > 0) {
				return RespBean.success("修改成功");
			} else return RespBean.error("修改失败");
		} else {

			Integer enabled = 1;
			int id1 = adminMapper.updateEnableById(enabled, (Integer) admin.get("id"));
			if (id1 > 0) {
				return RespBean.success("修改成功");
			} else return RespBean.error("修改失败");

		}
	}


}
